<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学生" prop="studentId">
        <el-select v-model="queryParams.studentId" filterable remote reserve-keyword placeholder="请输入学生编号"
          :remote-method="getStudentsByUserName" :loading="studentLoading" style="width: 240px">
          <el-option v-for="item in studentList" :key="item.userId" :label="item.nickName" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="请假状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择请假状态" clearable style="width: 240px;">
          <el-option v-for="dict in leave_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:request:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:request:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:request:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:request:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requestList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="请假记录ID" align="center" prop="leaveId" />
      <el-table-column label="学生" align="center" prop="studentId">
        <template #default="scope">
          <span>
            {{
              studentAll.find(student => student.userId === scope.row.studentId)?.nickName || '未知学生'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="请假开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假原因" align="center" prop="reason">
        <template #default="scope">
          <el-popover placement="top" width="200" trigger="hover">
            <p>{{ scope.row.reason }}</p>
            <template #reference>
              <span class="ellipsis">{{ scope.row.reason }}</span>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="请假状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="leave_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:request:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:request:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改请假管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="requestRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生" prop="studentId">
          <el-select v-model="form.studentId" filterable remote reserve-keyword placeholder="请输入学生编号"
            :remote-method="getStudentsByUserName" :loading="studentLoading" style="width: 240px">
            <el-option v-for="item in studentList" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="form.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm"
            format="YYYY-MM-dd HH:mm" placeholder="请选择请假开始时间" style="width: 240px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="form.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm"
            format="YYYY-MM-dd HH:mm" placeholder="请选择请假结束时间" style="width: 240px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="请假状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择请假状态">
            <el-option v-for="dict in leave_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Request">
import { listRequest, getRequest, delRequest, addRequest, updateRequest } from "@/api/manage/request";
import { allStudent } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { leave_status } = proxy.useDict('leave_status');

const requestList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const studentAll = ref([]);
const studentLoading = ref(false)
const studentList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: null,
    status: null,
  },
  rules: {
    studentId: [
      { required: true, message: "学生不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "请假开始时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "请假结束时间不能为空", trigger: "blur" }
    ],
    reason: [
      { required: true, message: "请假原因不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "请假状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);


// 传入的参数userName查询相关学生，通过allStudent接口查询所有学生
function getStudentsByUserName(queryParams) {
  if (queryParams) {
    studentLoading.value = true;
    allStudent({ userName: queryParams }).then(response => {
      studentLoading.value = false;
      studentList.value = response.rows;
    });
  } else {
    studentList.value = null;
  }
}

// 得到所有学生列表
function getAllStudent() {
  loading.value = true;
  allStudent().then(response => {
    studentAll.value = response.rows;
    getList();
    loading.value = false;
  });
}
getAllStudent();

/** 查询请假管理列表 */
function getList() {
  loading.value = true;
  listRequest(queryParams.value).then(response => {
    requestList.value = response.rows.filter(row => {
      const student = studentAll.value.find(student => student.userId === row.studentId);
      return student;
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    leaveId: null,
    studentId: null,
    startTime: null,
    endTime: null,
    reason: null,
    status: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("requestRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.leaveId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加请假管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _leaveId = row.leaveId || ids.value
  getRequest(_leaveId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改请假管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["requestRef"].validate(valid => {
    if (valid) {
      if (form.value.leaveId != null) {
        updateRequest(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRequest(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _leaveIds = row.leaveId || ids.value;
  proxy.$modal.confirm('是否确认删除请假管理编号为"' + _leaveIds + '"的数据项？').then(function () {
    return delRequest(_leaveIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/request/export', {
    ...queryParams.value
  }, `request_${new Date().getTime()}.xlsx`)
}

</script>

<style scoped>
/* 请假原因一列的样式 */
.ellipsis {
  display: inline-block;
  max-width: 150px;
  /* 根据需要调整宽度 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
</style>
